<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="success" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="offsale">下架</el-button>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="products" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="name" label="服务名称" width="120">
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="120">
      </el-table-column>
      <el-table-column prop="saleprice" label="销售价" width="120">
      </el-table-column>
      <el-table-column prop="salecount" label="销售数量" width="120">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100">
        <template scope="scope">
          <span v-if="scope.row.state==1" style="color: green">上架</span>
          <span v-else style="color: red">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="100">
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="100">
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="100">
      </el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>

				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :current-page="currentPage" :total="totals" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售数量" prop="salecount">
          <el-input v-model="saveForm.salecount" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="服务资源">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs/"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <quill-editor v-model="saveForm.productDetail.intro" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="服务须知" prop="orderNotice" >
          <quill-editor v-model="saveForm.productDetail.orderNotice" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

	export default {
    components: {
      quillEditor
    },
		data() {
			return {
        quillOption: quillConfig,
        products: [],
        totals: 0,
        currentPage: 1,
        pageSize: 5,
        listLoading: false,
        keyword:"",
        sels: [],//列表选中列

				saveFormVisible: false,//编辑界面是否显示
        title:"",
				saveLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入服务名称', trigger: 'blur' }
					]
				},
				//编辑界面数据
				saveForm: {
          id: null,
          name:'',
          costprice:0,
          saleprice:0,
          salecount:0,
          resources:'',
          productDetail:{  //与后端实体类一致
            intro: '',
            orderNotice: ''
          }
				},
        // 上传图片时，用于保存图片
        fileList:[]
			}
		},
		methods: {

      //获取服务列表
      getProducts() {
        let paras = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.keyword,
        };
        this.listLoading = true;
        this.$http.post("/product",paras).then(res=>{
          this.products=res.data.data;
          this.totals=res.data.totals;
          this.listLoading = false;
        }).catch(res=>{
          this.$message.error("系统繁忙，请稍后重试!!!");
        })
      },

      handleCurrentChange(val) {
        this.currentPage = val;
        this.getProducts();
      },

      keywordQuery(){
        this.currentPage=1;
        this.getProducts();
      },


      //删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.delete("/product/" + row.id).then(res=>{
            if (res.data.success){
              let totalPage = Math.ceil(this.totals/this.pageSize)
              if (this.currentPage == totalPage && (this.totals - 1)%this.pageSize == 0 && this.currentPage!=0){
                this.currentPage = this.currentPage - 1;
              }
              this.getProducts();
            } else {
              this.$message.error("系统繁忙，请稍后重试！！！")
            }
            this.listLoading = false;
          }).catch(res=>{
            this.$message.error("系统繁忙，请稍后重试！！！")
          })
        }).catch(() => {
        });
      },
      //批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.patch("/product",ids).then(res=>{
            if(res.data.success){
              this.currentPage = 1;
              this.getProducts();
            }else{
              this.$message.error("系统繁忙,请稍后再试！！！")
            }
            this.listLoading = false
          }).catch(res=>{
            this.$message.error("系统繁忙,请稍后再试！！！")
          })
        }).catch(() => {
        });
      },

      selsChange: function (sels) {
        this.sels = sels;
      },

			//显示编辑界面
			handleSave: function (index, row) {
        this.title = "修改";
        this.saveForm = Object.assign({}, row);
        this.fileList = [];
        if(this.saveForm.resources){
          let paths = this.saveForm.resources.split(",");
          for(var i = 0;i<paths.length;i++){
            this.fileList.push({"url":"http://123.207.27.208"+paths[i]})
          }
        }
				this.saveFormVisible = true;

			},
			//显示新增界面
			handleAdd: function () {
        this.title = "新增";
        this.saveForm = {
          id: null,
          name:'',
          costprice:0,
          saleprice:0,
          salecount:0,
          resources:'',
          productDetail:{  //与后端实体类一致
            intro: '',
            orderNotice: ''
          }
        };
        this.fileList=[];
        //弹出对话框
        this.saveFormVisible = true;
      },
			//编辑
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;

                this.$http.put("/product",this.saveForm).then(res=>{
                  if (res.data.success){
                    this.getProducts();
                  } else {
                    this.$message.error("系统繁忙，请稍后再试！！")
                  }
                  this.saveLoading = false;
                }).catch(res=>{
                  this.$message.error("系统繁忙，请稍后再试！！");
                  this.saveLoading = false;
                })
              this.saveFormVisible = false;
						});
					}
				});
			},
      // 点击删除图片时的处理，调用接口删图片
      handleRemove(file, fileList){
        // 调用删除接口删除图片
        var path = file.url.substring(file.url.indexOf("/group"));
        this.$http.delete("/fastDfs?path="+path).then(res=>{
          if(res.data.success){
            this.$message.success("删除成功")
          }else{
            this.$message.success("删除失败")
          }
        })

        // 对resource做处理
        if(this.saveForm.resources){
          var arr = this.saveForm.resources.split(",");
          for(var i = 0;i<arr.length;i++){
            var item = arr[i];
            if(path==item){//找到了删除的图片
              arr.splice(i,1);//删除指定的图片
            }
          }
          this.saveForm.resources = arr.join(",")
        }

        // 对fileList的处理 - 前端显示图片的
        this.fileList = [];
        if(this.saveForm.resources){
          var arr = this.saveForm.resources.split(",");
          for(var i = 0;i<arr.length;i++){
            var item = arr[i];
            this.fileList.push({"url":"http://123.207.27.208" + item});
          }
        }

      },
      // 图片上传成功之后的回调函数
      handleSuccess(response, file, fileList){
        //1.对resources的处理 - 添加到数据库
        if(this.saveForm.resources){//有值返回true
          this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
        }else{
          this.saveForm.resources = response.resultObj;
        }
        //2.对fileList的处理 - 前端显示图片的
        this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值
        if(this.saveForm.resources){
          var arr = this.saveForm.resources.split(",");
          for(var i = 0;i<arr.length;i++){
            var item = arr[i];
            this.fileList.push({"url":"http://123.207.27.208" + item});
          }
        }
      },
      // 上架
      onsale(){
        var ids = this.sels.map(item => item.id);//数组 [1,3,5]
        if(!ids || ids.length==0){
          this.$message.error("请选中再上架!!!!");
          return ;
        }

        this.$confirm('确认要上架选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => { //点击确定走这里
          this.$http.post("/product/onsale",ids).then(res=>{
            if(res.data.success){
              this.getProducts();
            }else{
              this.$message.error(res.data.msg);
            }
          }).catch(res=>{
            this.$message.error("系统异常，请稍后重试!!!400,404");
          })
        }).catch(() => {
        });
      },
      //服务下架
      offsale(){
        var ids = this.sels.map(item => item.id);//数组 [1,3,5]
        if(!ids || ids.length==0){
          this.$message.error("请选中再下架!!!!");
          return ;
        }

        this.$confirm('确认要下架选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => { //点击确定走这里
          this.$http.post("/product/offsale",ids).then(res=>{
            if(res.data.success){
              this.getProducts();
            }else{
              this.$message.error("下架失败");
            }
          }).catch(res=>{
            this.$message.error("系统异常，请稍后重试!!!400,404");
          })
        }).catch(() => {
        });
      }

		},
		mounted() {
			this.getProducts();
		}
	}

</script>

<style scoped>

</style>
